<template>
  <el-form ref="enrollFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="name">
      <el-input v-model="loginForm.name" placeholder="请输入姓名">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="mobile">
      <el-input v-model="loginForm.mobile" placeholder="请输入手机号码">
        <template #prefix>
          <el-icon class="el-input__icon">
            <Cellphone />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="sex">
      <el-select v-model="loginForm.sex" placeholder="请选择性别" clearable>
        <el-option
          v-for="item in genderType.filter(item => item.value)"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
        <template #prefix>
          <el-icon class="el-input__icon">
            <SvgIcon name="sex" />
          </el-icon>
        </template>
      </el-select>
    </el-form-item>
    <el-form-item prop="email">
      <el-input v-model="loginForm.email" placeholder="请填写邮箱" clearable>
        <template #prefix>
          <el-icon class="el-input__icon">
            <Message />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="departmentIdTemp">
      <el-cascader
        style="width: 100%"
        placeholder="所属组织架构"
        v-model="loginForm.departmentIdTemp"
        :options="departmentList"
        :props="{ checkStrictly: true, value: 'id', label: 'name', children: 'departmentModels' }"
        clearable
      >
      </el-cascader>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(enrollFormRef)"> 重置 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(enrollFormRef)">
      注册
    </el-button>
  </div>
  <div class="login-tip">
    <div class="login-tip-item" @click="registered">已有账号，立即登录</div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
// import { useRouter } from "vue-router";
// import { HOME_URL } from "@/config";
// import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
// import { ElNotification } from "element-plus";
import { userRegister } from "@/api/modules/sys";
// import { useUserStore } from "@/stores/modules/user";
// import { useTabsStore } from "@/stores/modules/tabs";
// import { useKeepAliveStore } from "@/stores/modules/keepAlive";
// import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import { getDict } from "@/api/modules/sys";
import { genderType } from "@/utils/serviceDict";
import { getCompanyDepart } from "@/api/modules/customer";
import mittBus from "@/utils/mittBus";
import { ElMessage } from "element-plus";
// import md5 from "md5";

// const router = useRouter();
// const userStore = useUserStore();
// const tabsStore = useTabsStore();
// const keepAliveStore = useKeepAliveStore();
const cxt = getCurrentInstance();
const dict = cxt?.appContext.config.globalProperties.$dict;

type FormInstance = InstanceType<typeof ElForm>;
const enrollFormRef = ref<FormInstance>();
const userStatus = ref();
const loginRules = reactive({
  name: [{ required: true, message: "请输入姓名" }],
  mobile: [{ required: true, pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/, message: "请填写手机号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  departmentIdTemp: [{ required: true, message: "请选择组织架构", trigger: "blur" }]
});
let departmentList = ref([]);

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  mobile: "",
  password: "",
  sex: "",
  name: "",
  email: "",
  departmentIdTemp: []
});

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口 // password: md5(loginForm.password)
      loginForm.departmentId = loginForm.departmentIdTemp.pop();
      delete loginForm.departmentIdTemp;
      await userRegister({ ...loginForm });
      ElMessage.success("注册成功");
      registered();
      mittBus.emit("iphone", loginForm.mobile);
      // console.log(data);
      // console.log(data);
      // 数据字典判断是否时启用的账户
      // let statusObj = userStatus.value.find(item => item.id === data.status);
      // if (!statusObj || statusObj.name == "禁用") {
      //   ElNotification({
      //     title: "温馨提示",
      //     message: "账号未启用， 请联系管理员",
      //     type: "error",
      //     duration: 3000
      //   });
      //   return;
      // }
      // 保存token
      // userStore.setToken(data.token);
      // 存储用户信息
      // userStore.setUserInfo(data);
      // userStore.setToken("");
      // 2.添加动态路由
      // await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      // tabsStore.closeMultipleTab();
      // keepAliveStore.setKeepAliveName();

      // 4.跳转到首页
      // router.push(HOME_URL);
      // ElNotification({
      //   title: getTimeState(),
      //   message: "欢迎登录" + import.meta.env.VITE_GLOB_APP_TITLE,
      //   type: "success",
      //   duration: 3000
      // });
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const getDepartmentFn = async () => {
  try {
    const { data } = await getCompanyDepart();
    if (data) {
      departmentList.value = data;
    }
  } catch (e) {
    console.log(e);
  }
};
const registered = () => {
  mittBus.emit("handoff", false);
};
onMounted(async () => {
  // 获取用户状态字典
  const { data } = await getDict({ parentId: dict.userStatus });
  userStatus.value = data || [];
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(enrollFormRef.value);
    }
  };
  getDepartmentFn();
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
